<?php
declare(strict_types=1);
/**
 * Date: 2021/12/21
 * Time: 11:38
 */

function get_start_time(): float
{
    return \App\Common\StartTime::getInstance()->getTime();
}

function set_start_time($time)
{
    \App\Common\StartTime::getInstance()->setTime($time);
}
function get_saas_id(): int
{
    return \App\Common\Saas::getInstance()->getId();
}

function set_saas_id($saas_id)
{
    \App\Common\Saas::getInstance()->setId($saas_id);
}

function getDb(string $name='db'): string
{
    $id = get_saas_id();
    $dbIndex = $id % env('DB_NUM', 1);

    return $name . '_' . $dbIndex;
}

function getTable(string $name): string
{
    $id = get_saas_id();
    $tableNum = env('TABLE_NUM', 1);
    $tableIndex = $id / $tableNum % $tableNum;

    return $name;
    //return $name . '_' . $tableIndex;
}

function get_current_db(): string
{
    return \App\Common\CurrentDb::getInstance()->getDb();
}

function set_current_db($db)
{
    \App\Common\CurrentDb::getInstance()->setDb($db);
}


if (! function_exists('array_only')) {
    /**
     * Get a subset of the items from the given array.
     *
     * @param  array  $array
     * @param  array|string  $keys
     * @return array
     */
    function array_only($array, $keys)
    {
        return array_intersect_key($array, array_flip((array) $keys));
    }
}

/**
 * Notes: int | string | bool | array to array
 * Author: Bruce.z
 * DateTime: 2021/12/21 16:41
 * @param $arg
 * @return array
 */
function toArray($arg) : array
{
    if(is_int($arg) || empty($arg) || is_bool($arg)) return [$arg];
    if(is_array($arg)) return $arg;

    return explode(',', $arg);
}

if (! function_exists('random')) {
    /**
     * Generate a more truly "random" alpha-numeric string.
     *
     * @param int $length
     * @param string $pool
     * @return string
     */
    function random(int $length = 16, string $pool = ''): string
    {
        if (!$pool) {
            $pool = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
        }
        return substr(str_shuffle(str_repeat($pool, $length)), 0, $length);
    }
}

/**
 * @param mixed $args
 * @return void
 */
function debug_log(...$args)
{
    \App\Utils\Log::getInstance()->debug(__METHOD__, $args);
}
